<?php

namespace app\command;

use app\api\controller\Work;
use app\common\controller\WeChat;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use app\common\service\MqttNewService;
use think\facade\Db;

class Mqtt extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('mqtt')
            ->setDescription('the mqtt command');
    }

    protected function execute(Input $input, Output $output)
    {
        $this->subscribe();
    }

    /**
     * 订阅接收消息
     */
    protected function subscribe()
    {
        $server   = '47.109.198.201';
        $port     = 1883;
        $clientId = 'test_emqx'. rand(1000000, 99999999);
        $topic    = "liquor/d/#";
        $username = "";
        $pwd      = "";
        $mqtt = new MqttNewService($server, $port, $clientId);
        if(!$mqtt->connect(true, NULL, $username, $pwd)) {
            exit(1);
        }
        $mqtt->debug = true;
        $topics[$topic] = array('qos' => 0, 'function' => array($this,"procMsg"));
        $mqtt->subscribe($topics, 0);
        while($mqtt->proc()) {
//            $data = $mqtt->subscribeAndWaitForMessage($topic, 0); // 接收数据
        }
        $mqtt->close();
    }

    function procMsg($topic, $msg){
        //所有消息返回记录
        Db::name('device_mqtt')->insert([
            'topic' => $topic,
            'content' => $msg,
            'create_time' => time(),
        ]);
        //业务逻辑处理
        $work = new Work();
        $topicArr = explode('/',$topic);
        $msgArr = json_decode($msg,true);
        switch ($topicArr[3]) {
            case 'dbInfo':
                //设备开机上报
                $device = Db::name('device')->where('imei',$msgArr['imei'])->find();
                if (empty($device)) {
                    $wechat = new WeChat();
                    $device_id = Db::name('device')->insertGetId([
                        'imei' => $msgArr['imei'],
                        'iccid' => $msgArr['iccid'],
                        'softversion' => $msgArr['softversion'],
                        'hardversion' => $msgArr['hardversion'],
                        'msgId' => $msgArr['msgId'],
                        'create_time' => time(),
                    ]);
                    $wx_code = $wechat->getQRCode($device_id);
                    Db::name('device')->where('id',$device_id)->update(['wx_code'=>$wx_code]);
                }
                //设备开机上报服务器返回
                $topic = 'liquor/s/'.$msgArr['imei'].'/dbInfo';
                $msg = json_encode([
                    "msgId"=> $msgArr['msgId'],
                    "status"=> "success",
                ]);
                $work->preOrder($topic,$msg);
                break;
            case 'status':
                //设备定时上报当前状态信息
                $device = Db::name('device')->where('imei',$topicArr[2])->find();
                if (!empty($device)) {
                    Db::name('device_log')->insert([
                        'imei' => $topicArr[2],
                        'msgId' => $msgArr['msgId'],
                        'status' => $msgArr['status'],
                        'weight' => $msgArr['weight'],
                        'device_status' => $msgArr['msg'],
                        'create_time' => time(),
                    ]);
                    Db::name('device')->where('id',$device['id'])->update([
                        'status' => $msgArr['status'],
                        'weight' => $msgArr['weight'],
                        'device_status' => $msgArr['msg'],
                        'update_time' => time(),
                    ]);
                }
                break;
            case 'control':
                //服务器下发控制设备返回信息
                if ($msgArr['instruct'] == 'replenish') {
                    //补酒设备返回
                    $device_bu = Db::name('device_bu')->where(['msgId'=>$msgArr['msgId']])->order('id desc')->find();
                    if (!empty($device_bu)) {
                        Db::name('device_bu')->where(['id'=>$device_bu['id']])->update([
                            'status' => $msgArr['status'],
                            'update_time' => time()
                        ]);
                    }
                }
                break;
            case 'order':
                //服务器下发订单创建设备返回信息,type:create
                //设备出酒暂停时上报出酒信息, type:run
                //设备上报出酒完成信息, type:finish

                break;
        }
        echo $msg;
    }
}

